//
//  WDWorderOrderMainVehScanCodeViewModel.m
//  wd-serviceapp
//
//  Created by Bin Tang on 2024/9/2.
//

#import "WDWorderOrderMainVehScanCodeViewModel.h"
#import <AVFoundation/AVFoundation.h>
#import "NSString+Json.h"


@interface WDWorderOrderMainVehScanCodeViewModel () <AVCaptureMetadataOutputObjectsDelegate>

@end

@implementation WDWorderOrderMainVehScanCodeViewModel

- (void)initialize
{
    [super initialize];
    
    _isShowLightBtn = YES;
    _isShowInputBtn = YES;
    
    CGSize scanSize = CGSizeMake(kScreenW * 3/4, kScreenW * 3/4);
    _scanRect = CGRectMake((kScreenW - scanSize.width)/2, (kScreenH - scanSize.height - BootomViewHeight)/2, scanSize.width, scanSize.height);
    
    
//    _reqModel = [WDTaskFinishInspectReqModel new];
//    _reqModel.engineerId = @([EDSAppDelegateTool sharedInstance].userInfoModel.id);
//    _reqModel.stationId = @([EDSAppDelegateTool sharedInstance].userInfoModel.stationId);
    
    
}

- (void)setupData {
    _reqModel.taskId = @(self.serviceModel.id);
}

- (UIImage *)imageWithName:(NSString *)imageName {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSURL *url = [bundle URLForResource:@"QRCodeScanView" withExtension:@"bundle"];
    NSBundle *imageBundle = [NSBundle bundleWithURL:url];
    NSString *fileName = [NSString stringWithFormat:@"%@@2x", imageName];
    NSString *path = [imageBundle pathForResource:fileName ofType:@"png"];
    return [[UIImage imageWithContentsOfFile:path] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

- (BOOL)isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL)isFrontCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL)isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL)isCameraAuthStatusCorrect{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusAuthorized || authStatus == AVAuthorizationStatusNotDetermined) {
        return YES;
    }
    return NO;
}

- (void)setupSession:(UIViewController *)vc {
    [self authorizationCheck];
    
    //获取摄像设备
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error;
    
    //创建输入流
    self.deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    
    //创建输出流
    self.dataOutput = [[AVCaptureMetadataOutput alloc] init];
    [self.dataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
   
    
    self.session = [[AVCaptureSession alloc] init];
    
    if ([self.device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1920x1080]) {
        [self.session setSessionPreset:AVCaptureSessionPreset1920x1080];
    }
    else
    {
        [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    }
    
    //  拍摄会话 - 判断能够添加设备
    if (![self.session canAddInput:self.deviceInput]){
        NSLog(@"无法添加输入设备deviceInput");
        self.session = nil;
        return;
    }
    
    if (![self.session canAddOutput:self.dataOutput]){
        NSLog(@"无法添加输入设备dataOutput");
        self.session = nil;
        return;
    }
    
    // 添加输入／输出设备
    [self.session addOutput:self.dataOutput];
    [self.session addInput:self.deviceInput];

    self.dataOutput.metadataObjectTypes = self.dataOutput.availableMetadataObjectTypes;
    
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = vc.view.frame;
    [vc.view.layer insertSublayer:self.previewLayer atIndex:0];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (![self.session isRunning]) {
            [self.session startRunning];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dataOutput.rectOfInterest = [self.previewLayer metadataOutputRectOfInterestForRect:self.scanRect];
        });
    });
    

    //放大焦距
    [self.device lockForConfiguration:&error];
    if (self.device.activeFormat.videoMaxZoomFactor > 2) {
        self.device.videoZoomFactor = 1.5;
    }else{
        self.device.videoZoomFactor = self.device.activeFormat.videoMaxZoomFactor;
    }
    [self.device unlockForConfiguration];
}

//相机权限检测
- (BOOL)authorizationCheck {
    if (![self isCameraAvailable]){
        [SVProgressHUD showInfoWithStatus:@"设备无相机功能，无法进行扫描"];
        return NO;
    }
    if (![self isRearCameraAvailable] && ![self isFrontCameraAvailable]) {
        [SVProgressHUD showInfoWithStatus:@"设备相机错误,无法启用相机,请检查"];
        return NO;
    }
    if (![self isCameraAuthStatusCorrect]) {
        [SVProgressHUD showInfoWithStatus:@"相机权限未开启,请进入系统[设置] > [隐私] > [相机] 中打开开关"];
        return NO;
    }
    return YES;
}

/// 开始扫描
- (void)startScan:(void (^)(void))completion {
    if (![self authorizationCheck]) {
        return;
    }
    if (completion) {
        completion();
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (![self.session isRunning]) {
            [self.session startRunning];
        }
    });
}

/// 停止扫描
- (void)stopScan:(void (^)(void))completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
        if ([self.session isRunning]) {
            [self.session stopRunning];
        }
    });
    if (completion) {
        completion();
    }
}

- (void)turnTorch:(BOOL)on {
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        if ([device hasTorch] && [device hasFlash]){
            
            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
                
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects.count > 0 && metadataObjects != nil)
    {
        @weakify(self);
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects firstObject];
        
        if ([metadataObject isKindOfClass:[AVMetadataMachineReadableCodeObject class]]) {
            
            NSString *scanCode = [NSString stringWithFormat:@"%@",[metadataObject stringValue]]; //扫描结果
            NSString *scanType = [NSString stringWithFormat:@"%@",[metadataObject type]]; //扫描类型
            if (scanCode != nil) {
                [self stopScan:^{
                    @strongify(self);
                    if (self.touchScanCodeResultBlock) {
                        self.touchScanCodeResultBlock(scanCode, scanType);
                    }
                }];
            } else {
                [SVProgressHUD showErrorWithStatus:@"无效二维码"];
//                [SVProgressHUD showErrorWithStatus:@"扫码失败，请重新扫码或手动输入车辆底盘号或车辆车牌号进行识别"];
//                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }
}


/// 完成检查 开始维修
/// - Parameter completion: completion description
- (void)requestWithTaskFinishInspect:(RequestCompletionBlock)completion {
    @weakify(self);
    WDArrivalFinishRepairRequest *request = [[WDArrivalFinishRepairRequest alloc] initWithModel:self.reqModel];
    [request startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        [self sendResponseObject:request.responseModelObject completion:completion];
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
        @strongify(self);
        
        [self sendResponseObject:request.responseModelObject completion:completion];
    }];
}

@end
